# !/usr/bin    python3
# encoding:    utf-8 -*-
# @file        : conftest.py
# @author      : 加强 jqlin
# @Time        : 2025/9/30 9:41
# @Copyright:  : 接口自动化

from typing import List
import pytest
from api.base_api import BaseBuyerApi, BaseSellerApi
from api.buyer.login_apis import BuyerLoginApi
from api.seller.login_apis import SellerLoginApi
from common.logger import GetLogger


def pytest_collection_modifyitems(items:List["Item"]):  # Alt + Shift + Enter
    # items对象是pytest收集到的所有用例对象
    for item in items:
        # item就代表了一条用例
        item._nodeid = item._nodeid.encode('utf-8').decode("unicode-escape")

@pytest.fixture(scope='session',autouse=True)
def aalogger_init():
    GetLogger.get_logger().info('日志初始化成功')

@pytest.fixture(scope='session',autouse=True)
def buyer_login():
    # 实例化买家登录的接口类对象，完成调用，提取token，赋值给BaseBuyerApi.buyer_token
    resp = BuyerLoginApi(username='mtx-001',password='123456').send()
    # 打印完整的响应信息用于调试
    print(f'登录接口响应状态码:{resp.status_code}')
    print(f"登录接口响应内容:{resp.json}")

    # # 检查响应中是否包含 access_token
    # if 'access_token' in resp.json():
    #     BaseBuyerApi.buyer_token = resp.json()['access_token']
    #     print("成功获取 access_token")
    # else:
    #     # 尝试其他可能的字段名
    #     response_data = resp.json()
    #     possible_token_keys = ['access_token', 'token', 'accessToken', 'auth_token']
    #     token_found = False
    #
    #     for key in possible_token_keys:
    #         if key in response_data:
    #             BaseBuyerApi.buyer_token = response_data[key]
    #             print(f"使用字段 '{key}' 作为 token")
    #             token_found = True
    #             break
    #
    #     if not token_found:
    #         print("错误: 响应中未找到 token 字段")
    #         print("可用字段:", list(response_data.keys()))
    #         # 这里可以根据需要决定是否抛出异常
    #         BaseBuyerApi.buyer_token = None
    BaseBuyerApi.buyer_token = resp.json()['access_token']

@pytest.fixture(scope='session',autouse=True)
def seller_login():
    # 实例化卖家登录的接口类对象，完成调用，提取token，赋值给BaseSellerApi.seller_token
    resp = SellerLoginApi(username='mtx-001',password='123456').send()
    BaseSellerApi.seller_token = resp.json()['access_token']